//
//  UITextView+PPKit.swift
//  PPKit
//
//  Created by xiaopin on 2019/8/28.
//  Copyright © 2019 PPKit. All rights reserved.
//  https://gitee.com/xiaopindev/PPKit
//  https://github.com/xiaopindev
//  https://xiaopin.cnblogs.com

extension UITextView: UITextViewDelegate {
    
    /// Resize the placeholder when the UITextView bounds change
    override open var bounds: CGRect {
        didSet {
            self.resizePlaceholder()
        }
    }
    
    /// When the UITextView did change, show or hide the label based on if the UITextView is empty or not
    ///
    /// - Parameter textView: The UITextView that got updated
    public func textViewDidChange(_ textView: UITextView) {
        if let placeholderLabel = self.viewWithTag(100) as? UILabel {
            placeholderLabel.isHidden = self.text.count > 0
        }
    }
    
    /// Resize the placeholder UILabel to make sure it's in the same position as the UITextView text
    private func resizePlaceholder() {
        if let placeholderLabel = self.viewWithTag(100) as! UILabel? {
            let labelX = self.textContainer.lineFragmentPadding
            let labelY = self.textContainerInset.top - 2
            let labelWidth = self.frame.width - (labelX * 2)
            let labelHeight = placeholderLabel.frame.height
            
            placeholderLabel.frame = CGRect(x: labelX, y: labelY, width: labelWidth, height: labelHeight)
        }
    }
    
    /// Adds a placeholder UILabel to this UITextView
    private func addPlaceholder(_ placeholderText: String) {
        let placeholderLabel = UILabel()
        
        placeholderLabel.text = placeholderText
        placeholderLabel.sizeToFit()
        
        placeholderLabel.font = self.font
        placeholderLabel.textColor = UIColor.lightGray
        placeholderLabel.tag = 100
        
        placeholderLabel.isHidden = self.text.count > 0
        
        self.addSubview(placeholderLabel)
        self.resizePlaceholder()
        self.delegate = self
    }
    
}

extension UITextView {
    
    ///一行快捷生成UITextView
    convenience init(font:UIFont = .systemFont(ofSize: 12, weight: .regular),
                     textColor:UIColor? = .black,
                     bgColor:UIColor? = .clear,
                     placeholder:String?=nil,
                     placeholderColor:UIColor = .lightGray,
                     align:NSTextAlignment = .left) {
        self.init()
        self.textColor = textColor
        self.backgroundColor = bgColor
        self.font = font
        self.placeholder = placeholder ?? ""
        self.placeholderColor = placeholderColor
        self.textAlignment = align
    }

    private struct RuntimeKey {
        static let hw_placeholderLabelKey = UnsafeRawPointer.init(bitPattern: "hw_placeholderLabelKey".hashValue)
        /// ...其他Key声明
    }

    /// 占位文字
    @IBInspectable public var placeholder: String {
        get {
            return self.placeholderLabel.text ?? ""
        }
        set {
            self.placeholderLabel.text = newValue
        }
    }

    /// 占位文字颜色
    @IBInspectable public var placeholderColor: UIColor {
        get {
            return self.placeholderLabel.textColor
        }
        set {
            self.placeholderLabel.textColor = newValue
        }
    }

    private var placeholderLabel: UILabel {
        get {
            var label = objc_getAssociatedObject(self, UITextView.RuntimeKey.hw_placeholderLabelKey!) as? UILabel
            if label == nil {
                if (self.font == nil) {
                    self.font = UIFont.systemFont(ofSize: 15.scale)
                }
                label = UILabel.init(frame: self.bounds)
                label?.numberOfLines = 0
                label?.font = self.font
                label?.textColor = UIColor.lightGray
                self.addSubview(label!)
                self.setValue(label!, forKey: "_placeholderLabel")
                objc_setAssociatedObject(self, UITextView.RuntimeKey.hw_placeholderLabelKey!, label!, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
                self.sendSubviewToBack(label!)
            }
            return label!
        }
        set {
            objc_setAssociatedObject(self, UITextView.RuntimeKey.hw_placeholderLabelKey!, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }

}


extension UITextField {
    ///快捷生成UITextField
    convenience init(_ fontSize:CGFloat,
                     weight:UIFont.Weight = .regular,
                     textColor:UIColor? = .black,
                     placeholder:String?=nil,
                     placeholderColor:UIColor = .lightGray,
                     align:NSTextAlignment = .left) {
        self.init()
        self.textColor = textColor
        self.clearButtonMode = .whileEditing
        self.font = UIFont.systemFont(ofSize:fontSize, weight:weight)
        self.placeholder = placeholder
        if placeholder != nil {
            self.attributedPlaceholder = NSAttributedString(string: placeholder!, attributes: [NSAttributedString.Key.foregroundColor:placeholderColor])
        }
        self.textAlignment = align
    }
    
    class func leftSpacingField(fontSize:CGFloat,placeholder:String? = nil, placeholderColor:UIColor = .lightGray, spacing:CGFloat) -> UITextField {
        let field = UITextField()
        field.textColor = .black
        field.clearButtonMode = .whileEditing
        field.font = UIFont.systemFont(ofSize:fontSize)
        field.placeholder = placeholder
        if placeholder != nil {
            field.attributedPlaceholder = NSAttributedString(string: placeholder!, attributes: [NSAttributedString.Key.foregroundColor:placeholderColor])
        }
        field.autocorrectionType = .no
        field.keyboardType = UIKeyboardType.alphabet
        field.tintColor = .black
        field.autocapitalizationType = .none
        field.leftView = UIView(frame: CGRect(x:0,y:0,width:spacing,height:0))
        field.leftViewMode = .always
        return field
    }
}
